<template>
  <div class="zd-yqTemp">

    <el-tabs v-model="intensityGroup" type="card">
      <el-tab-pane label="A-AA" name="1">
      </el-tab-pane>
      <el-tab-pane label="A-A" name="2">
      </el-tab-pane>
      <el-tab-pane label="B" name="3">
      </el-tab-pane>
    </el-tabs>

    <!---->
    <div class="zd-yqTemp__content" v-loading="loading">
      <el-row class="content-header">
        <el-col :span="5" class="content-cell">
          <div class="content-hidden ">***</div>
        </el-col>
        <el-col :span="19" class="content-cell">
          <div>周日程</div>
        </el-col>
      </el-row>

      <el-row v-for="(n,index) in tempList.length" :key="index" class="label-row">
        <el-col :span="5" class="content-cell content-label">
          <div v-if="userState=='1' || userState=='3'">第{{index}}周</div>
           <div v-else-if="userState=='4'">第{{index + 156}}周</div>
          <div v-else>{{getTemplateTitle(index)}}</div>
        </el-col>
        <el-col :span="5">
          <div class="content-hidden ">***</div>
        </el-col>
        <el-col :span="19" class="content-cell">
          <div class=" cell-value" v-if="tempList[index] && tempList[index].list">
            <div v-for="(item,ins) in tempList[index].list" :key="item.id" class="cell-item">
              <span class="cell-color" :style="{'background-color':item.Color}"></span>
              <span :style="{'font-weight':item.IsFontWeight=='1'?'700':'400'}">{{item.Title}}</span>
              <!-- <span v-if="item.NeedFollowUp=='1'">{{'('+ FollowUpTypeFormater(0,0,item.FollowUpType) +')'}}</span> -->
              <span v-if="item.FollowUpType=='2'"> <img class="img-follow" :src="icon_tel" alt="" /> </span>
              <span v-if="item.FollowUpType=='1'"> <img class="img-follow" :src="icon_talk" alt="" /> </span>
              <span v-if="item.NeedQuestionnaire=='1'"> <img class="img-follow" :src="icon_ques" alt="" /> </span>
              <el-button class="button-closes" style="right:80px;" size="small" type="text" @click="changePositionHandler(1,index,item,ins)">
                <span class="arrow-top"></span>
              </el-button>
              <el-button class="button-closes"  style="right:50px;" size="small" type="text" @click="changePositionHandler(-1,index,item,ins)">
                <span class="arrow-bottom"></span>
              </el-button>
              <span @click="deleteHandler(index,item)" class="button-close"></span>
            </div>
          </div>
          <div v-else class=" cell-value" style="text-align:center;">
            无基本事项
          </div>

          <el-button class="cell-button" @click="addHandler(index)" type="primary" plain>
            <span class="button-label">+添加事项</span>
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 编辑查看对话框 -->
    <keep-alive>
      <el-dialog title="选择待办事项" :close-on-click-modal="false" v-loading="loadingDialog"
                 :visible.sync="centerDialogVisible" width="60%" :append-to-body="true" top="0">

        <div class="query-area">
          <el-input v-model="keyword" placeholder="待办事项标题关键字" class="header-query"></el-input>
          <el-button type="primary" @click="queryHandler" size="middle">查询</el-button>
        </div>

        <el-table :data="tableData" @select="handleSelect" @select-all="handleSelect" ref="multipleTable" border empty-text="当前列表为空" v-loading="loading" height="300" element-loading-text="加载中" style="width: 100%">
          <el-table-column type="selection" align="center" width="38">
          </el-table-column>
          <el-table-column header-align="center" prop="Title" label="待办事项标题" min-width="200">
          </el-table-column>

          <el-table-column align="center" :formatter="Fllowformater" prop="NeedFollowUp" label="事项类型" min-width="70">
          </el-table-column>

          <el-table-column align="center" :formatter="FollowUpTypeFormater" prop="FollowUpType" label="访谈类型" min-width="70">
          </el-table-column>

          <el-table-column align="center" :formatter="TFformater" prop="NeedQuestionnaire" label="填写问卷" min-width="70">
          </el-table-column>

          <el-table-column align="center" prop="Description" label="具体描述" min-width="100">
          </el-table-column>
        </el-table>

        <!--分页-->
        <div class="block mg-20-auto">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="pageCount" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveHandler">保 存</el-button>
        </span>
      </el-dialog>
    </keep-alive>
  </div>
</template>
<script>
export default {
  name: "yqTemp1",
  props: {
    // tableData: {
    //   type: Array,
    //   required: true
    // },
    // 用户状态， 1:孕前期日程模板，2：孕期日程模板
    userState: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      icon_tel: require("../../../src/assets/images/icon_tel.png"),
      icon_talk: require("../../../src/assets/images/icon_talk.png"),
      icon_ques: require("../../../src/assets/images/icon_ques.png"),
      searchData: {
        name: "",
        number: ""
      },
      tableData: [],
      arrLength: this.userState == "1" ? 53:this.userState == "2" ? 41 : this.userState == "3" ? 156 :105,
      tempList: new Array(this.arrLength),
      form: {
        dictTypeName: "",
        cscode: ""
      },
      intensityGroup: "1", // 干预组别  1:高强度干预组，2：低强度干预组，3：常规护理组
      formRules: {
        dictTypeName: [
          { required: true, message: "请填写地点名称", trigger: "blur" }
        ],
        cscode: [{ required: true, message: "请填写地点编号", trigger: "blur" }]
      },
      centerDialogVisible: false,
      formLabelWidth: "120px",
      total: null,
      pageSize: 10,
      pageCount: 1,
      keyword: "",
      loading: false,
      loadingDialog: false,
      multipleSelection: [],
      currentSeltection: [],
      TimeSpan: "0" // 备孕周数或孕周
    };
  },
  watch: {
    userState(value) {
      this.getList();
    },
    intensityGroup(value) {
      this.getList();
    }
  },
  methods: {
    getBacklogContent(id) {
      let content = "";
      let that = this;
      that.tableData.some(data => {
        if (data.SYS_ID === id) {
          content = data;
          return true;
        }
      });

      return content;
    },
    Fllowformater:function(row, column, cellValue, index){
      switch(cellValue){
        case '1':
          return '健康访谈';
        case '2':
          return '营养门诊';
        case '3':
          return '健康教育';
	    case '5':
		      return '母乳喂养随访';
	    case '6':
		      return '数据采集';
	    case '6':
		      return '数据采集';
        default:
          return '其它事项'
      }
    },
    FollowUpTypeFormater(row, column, cellValue, index) {
      return row.NeedFollowUp==1?(cellValue ? (cellValue == 1 ? "面对面" : "电话") : "-"):'-';
    },
    changePositionHandler(direction, index, row,ins) {
      // direction:1: 向上， -1 ： 向下；
      let tmpIndex;
      let that = this;
      console.log(row)
      let tmpItem;
      if (direction == 1) {  //向下
        if (ins <= 0) {
          return;
        }
          row.SortIndex-=1
      } else {
        if (ins >= that.tempList[index].list.length - 1) {
          return;
        }                    //向上
        row.SortIndex+=1
      }

      that.service({
          url: "Dic/SaveScheduleTemplateIndex",
          method: "post",
          data: {
               ...row
          }
          })
          .then(response => {
              that.tempList[index].list.splice(ins,1)
              that.tempList[index].list.splice(ins-direction,0,row)
              that.$message({
                message:'保存成功',
                type:'success'
              })
          }).catch(data => {
            that.$message({
              message:'保存失败',
              type:'info'
            })
      });
    },
    getTemplateTitle(index) {
      if (index + 5 <= 41) {
        return `孕${index + 5}周`;
      } else if (index + 5 == 42) {
        return "分娩前";
      } else if (index + 5 == 43) {
        return "分娩后";
      } else if (index + 5 == 44) {
        return "产科病房";
      } else if (index + 5 == 45) {
        return "产后42天门诊";
      }
    },
    addHandler(index) {
      this.TimeSpan = this.userState == 2 ? index + 5 : this.userState == 4 ? index + 156 : index;
      this.centerDialogVisible = true;
      this.multipleSelection=[]
      this.keyword = "";
      this.getBacklog();
      this.loading = false;
      this.$nextTick(() => {

      });
    },
    TFformater(row, column, cellValue, index) {
      return cellValue == 1 ? "是" : "否";
    },

    queryHandler() {
      this.pageCount = 1;
      this.getBacklog();
    },
    deleteHandler(index, row) {
      this.$confirm("是否删除本事项？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let that = this;
          that
            .service({
              url: "Dic/DeleteScheduleTemplate?sysId=" + row.SYS_ID,
              method: "post"
            })
            .then(resp => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });

              that.getList();
              // that.tableData.push(that.form);
            })
            .catch(data => {
              that.loading = false;
            });
        })
        .catch(() => {});
    },
    handleSizeChange(val) {
      //条数改变
      this.pageSize = val;
      // this.multipleSelection = this.multipleSelection;
      this.getBacklog();
      // 处理选中
    },
    handleCurrentChange(val) {
      //页数改变
      this.pageCount = val;
      // this.multipleSelection = this.multipleSelection;
      this.getBacklog();

    },
    getBacklog() {
      let that = this;
      that
        .service({
          url: "Dic/GetBacklog",
          method: "get",
          params: {
            pageCount: that.pageCount - 1,
            pageSize: that.pageSize,
            blackLogTitle: that.keyword,
            type:'',
            roleGroup:'1'
          }
        })
        .then(response => {
          // console.log(response.dtData);
          that.tableData = response.dtData;
          that.total = parseInt(response.dtData[0].TotalCount);
          that.loading = false;
          that.$nextTick(() => {
            that.handleToggleRowSelection();
          });
        })
        .catch(data => {
          that.loading = false;
        });
    },
    removeArrayItem(array, item) {
      var index = array.indexOf(item);
      if (index > -1) {
        array.splice(index, 1);
      }
    },
    // 处理全选
    handleSelect(selection, row) {
      // 根据选项和选择结果判断是添加还是删除
      if (row) {
        if (selection.indexOf(row) !== -1) {
          // 添加某项，暂时不做处理
        } else {
          // 删除某项
          this.removeArrayItem(this.multipleSelection, row);
        }
      }

      // length >0 则为全选，否则为全部取消
      if (selection.length > 0) {
        this.multipleSelection.push.apply(this.multipleSelection, selection);
        // 数据去重
        this.multipleSelection = Array.from(new Set(this.multipleSelection));
      } else {
        this.tableData.forEach(select => {
          this.removeArrayItem(this.multipleSelection, select);
        });
      }
    },
    // 处理选中项
    handleToggleRowSelection() {
      // console.log("处理....");
      let _this = this;
      this.tableData.forEach(select => {
        _this.multipleSelection.forEach(mul => {
          if (select.SYS_ID == mul.BacklogId || select.SYS_ID == mul.SYS_ID) {
            _this.$refs.multipleTable.toggleRowSelection(select, true);
          }

        });
      });
    },
    getList() {
      let that = this;
      that.loading = true;
      that.tempList = new Array(this.arrLength);
      console.log(that.tempList)
      that
        .service({
          url: "Dic/GetScheduleTemplate",
          method: "get",
          params: {
            userState: that.userState,
            intensityGroup: that.intensityGroup
          }
        })
        .then(response => {
          let dataList = response.dtData;
          dataList.forEach(data => {
            let currentIndex =
              that.userState == 1 ? 
              data.TimeSpan :that.userState == 2?
              data.TimeSpan - 5 : that.userState == 4 ? data.TimeSpan - 156 :data.TimeSpan;
            let timeArr = that.tempList[currentIndex] || [];
            that.$set(that.tempList, currentIndex, timeArr);

            let tmp = typeof that.tempList[currentIndex] == "object" && that.tempList[currentIndex].list ? that.tempList[currentIndex].list.concat()
                : [];

            tmp.push(data);

            that.$set(that.tempList[currentIndex], "list", tmp);
          });
          that.loading = false;
        })
        .catch(data => {
          that.loading = false;
        });
    },
    searchHandler() {
      this.pageCount = 1; // 分页索引
      this.getList();
    },
    saveHandler() {
      let that=this;
      if (that.multipleSelection.length <= 0) {
        return;
      }
      that.centerDialogVisible = false;
      that.multipleSelection.forEach((selection, index) => {
            selection.UserState= that.userState
            selection.IntensityGroup=that.intensityGroup
            selection.TimeSpan=that.TimeSpan
            selection.BacklogId=selection.SYS_ID
            delete selection.SYS_ID
      });
  that.saveScheduleTemplate(that.multipleSelection);
      // this.getList();
    },
    saveScheduleTemplate(data, index) {
      this.loadingDialog = true;
      let that = this;
      that
        .service({
          url: "Dic/SaveScheduleTemplate",
          method: "post",
          data: {
            ListScheduleTemplateObj:data
          }
        })
        .then(response => {
          console.log("save....");
          console.log(response);
          this.loadingDialog = false;
          this.getList();
        })
        .catch(data => {
          that.loading = false;
        });
    }
  },
  mounted() {
    this.getList();
  },
  components: {}
};
</script>
<style lang="scss">
.content-hidden {
  visibility: hidden;
}

.label-row {
  position: relative;
  border-left: 1px solid #cccccc;
  // display: flex;
  // justify-content: center;
  // flex-direction: column;
  .content-label {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.content-header {
  height: 60px;
  line-height: 60px;
  text-align: center;
  background-color: #f5f7fb;
  border-top: 1px solid #cccccc;
  border-left: 1px solid #cccccc;
}
.content-cell {
  text-align: center;
  border: 1px solid #cccccc;
  border-width: 0 1px 1px 0;
}

.cell-button {
  width: 80px;
  height: 24px;
  line-height: 24px;
  margin: 10px 0 14px 0;
  position: relative;
  .button-label {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    margin: auto;
    font-size: 12px;
  }
}

.cell-value {
  text-align: left;
  position: relative;
  font-size: 14px;
  margin-top: 14px;
  color: #333333;
  .cell-item {
    position: relative;
    padding: 6px 0;
    line-height: 100%;
    &:hover {
      background: #eaf6ff;
    }
    .cell-color {
      display: inline-block;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background-color: #dddddd;
      margin: 0 6px;
    }
    .img-follow {
      margin: 1px 0 0 5px;
      vertical-align: bottom;
      // height: 14px;
      // width: 14px;
    }
    .button-closes{
      display: block;
      position: absolute;
      width: 12px;
      height: 12px;
      right: 8px;
      top: 4px;
    }
    .button-close {
      display: block;
      position: absolute;
      width: 12px;
      height: 12px;
      right: 8px;
      top: 4px;
      &::before {
        content: "";
        position: absolute;
        top: 8px;
        width: 16px;
        height: 2px;
        background-color: #dddddd;
        transform: rotate(45deg);
      }
      &::after {
        content: "";
        position: absolute;
        top: 8px;
        width: 16px;
        height: 2px;
        background-color: #dddddd;
        transform: rotate(-45deg);
      }
    }
  }
}

.zd-yqTemp__content {
  width: 60%;
}

.zd-yqTemp .el-dialog__wrapper .el-dialog .el-dialog__footer {
  text-align: center;
}

.query-area {
  display: flex;
  width: 50%;
  margin-bottom: 10px;
}

.header-query {
  // width: 70%;
  margin-right: 15px;
  display: inline-block;
}
.arrow-top {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  width: 8px;
  height: 8px;
  border: 1px solid #409eff;
  border-width: 1px 0 0 1px;
  transform: rotate(45deg) translateY(-50%);
&::before {
   content: "";
   position: absolute;
   height: 1px;
   width: 12px;
   background-color: #409eff;
   left: 0;
   top: -1px;
   transform: rotate(45deg);
   transform-origin: 0 0;
 }
}

.arrow-bottom {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  width: 8px;
  height: 8px;
  border: 1px solid #409eff;
  border-width: 0 1px 1px 0;
  transform: rotate(45deg);
&::before {
   content: "";
   position: absolute;
   height: 1px;
   width: 12px;
   background-color: #409eff;
   right: 0;
   bottom: 0;
   transform: rotate(45deg);
   transform-origin: 100% 0;
 }
}

.yqtemp-list__dialog .el-dialog {
  max-height: 90%;
  margin-top: 5vh !important;
  overflow-y: scroll;
}

.yqtemp-list__dialog .el-dialog .el-dialog__body {
  padding: 15px;
}
</style>